<template>
  <div class="wx-login">
    <van-nav-bar left-text="返回" left-arrow @click-left="router.back()" />
  </div>
</template>

<script setup lang="ts">
import API from '@/api';
import { showSuccessToast, showFailToast, showLoadingToast, closeToast } from 'vant';
import { useRouter } from "vue-router";

const router = useRouter();

// 判断是否接受到code
const code = new URLSearchParams(window.location.search).get('code');
if (code) {
  // 调用后端接口，登录
  showLoadingToast("登录中...");
  API.userController.wxLogin({ code, state: '' }).then(res => {
    closeToast();
    if (res.data.code === 200) {
      showSuccessToast("登录成功");
      router.push({
        path: "/",
        replace: true,
      });
    } else {
      showFailToast("登录失败，" + res.data.message);
      router.push({
        path: "/auth/login",
        replace: true,
      });
    }
    // 去除url中的code和state参数
    const url = new URL(window.location.href);
    url.searchParams.delete('code');
    url.searchParams.delete('state');
    window.history.replaceState({}, '', url.toString());
  });
} else {
  // 调用微信登录
  wxLogin();
}

async function wxLogin() {
  // 获取appId
  const info = await API.userController.wxLoginInfo();
  const appId = info.data.data?.wxAppId;
  // 构造微信登录链接
  const redirectUri = encodeURIComponent(window.location.href);
  const state = '';

  const wxLoginUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;

  window.location.href = wxLoginUrl;
}

</script>

<style scoped></style>